import CryptoJS from 'crypto-js'

const KEY = 'E20D383FE1E53A1D'

interface Params {
  userId: number
  token: string
}

/**
 * userId+|$$|+token+|$$|+random+|$$|+timeStamp
 */
export default function genSignParams(params: Params, data: any) {
  const signParams = {
    userId: params.userId,
    token: params.token,
    random: Math.random()
      .toString(36)
      .substr(2, 15),
    timeStamp: new Date().getTime(),
  }

  const sign = getSign(signParams, KEY)

  return {
    ...data,
    userId: signParams.userId,
    random: signParams.random,
    timeStamp: signParams.timeStamp,
    sign,
  }
}

/**
 *
 */
function getSign(params: { [key: string]: any }, key: string) {
  const joinStr = '|$$|'

  const encryptStr = Object.values(params).join(joinStr)

  return encrypt(encryptStr, key)
}

function encrypt(word: string, keyStr: string) {
  // keyStr = keyStr ? keyStr : 'E20D383FE1E53A1D'
  const key = CryptoJS.enc.Utf8.parse(keyStr) //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

// 解密
function decrypt(word: string, keyStr: string) {
  const key = CryptoJS.enc.Utf8.parse(keyStr) //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  const decryptStr = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decryptStr).toString()
}
